import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class register extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //解决中文乱码
       request.setCharacterEncoding("UTF-8");
       //获取表单提交的数据
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        //JDBC连接数据库
        Connection conn=null;
        PreparedStatement ps=null;
        int count=0;
        try {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            conn= DriverManager.getConnection("jdbc:mysql://localhost/bjpowernode","root","19970913Xun");
            //关闭自动提交机制
            conn.setAutoCommit(false);
            //获取数据库操作对象
            String sql = "insert into t_user (username,password)values(?,?)";
            ps=conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            //执行sql语句
            count=ps.executeUpdate();
            //提交事务
            conn.commit();
        } catch (ClassNotFoundException e) {
            if (conn!=null){
                try {
                    conn.rollback();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        if (count==1){
           //转发刷新会导致创建多个用户
           // request.getRequestDispatcher("/success.html").forward(request,response);
           //使用重定向
           response.sendRedirect(request.getContextPath()+"/success.html");
        }
    }
}
